import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { UserVO } from '@/types/api'
import { login as loginApi, logout as logoutApi, getCurrentUser } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserVO | null>(null)
  const isLogin = ref(false)

  /**
   * 登录
   */
  const login = async (username: string, password: string) => {
    const res = await loginApi({ username, password })
    userInfo.value = res.data
    isLogin.value = true
    return res.data
  }

  /**
   * 登出
   */
  const logout = async () => {
    try {
      // 调用后端 logout 接口清除 session
      await logoutApi()
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      // 无论是否成功，都清除前端状态
      userInfo.value = null
      isLogin.value = false
    }
  }

  /**
   * 获取当前用户信息
   */
  const fetchUserInfo = async () => {
    try {
      // 从后端 session 中获取当前用户信息
      const res = await getCurrentUser()
      userInfo.value = res.data
      isLogin.value = true
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 获取失败说明未登录或 session 已过期
      userInfo.value = null
      isLogin.value = false
      throw error
    }
  }

  /**
   * 检查是否是管理员
   */
  const isAdmin = () => {
    return userInfo.value?.role === 0
  }

  return {
    userInfo,
    isLogin,
    login,
    logout,
    fetchUserInfo,
    isAdmin,
  }
})

